/**
 * @Author: leibidong
 * @Description:库存管理service层
 * @File:  warehouseProductService
 * @Version: 1.0.0
 * @Date: 2021/7/6 19:00
 */

package service

import (
	"encoding/json"
	"ginProject/biz/dao"
	"ginProject/biz/model"
	"ginProject/biz/utils"
	"ginProject/biz/vo"
	"github.com/go-redis/redis"
	"time"
)

/**
 * @Author leibidong
 * @Description 根据商品id查询商品service层
 * @Date  2021/7/6 19:57
 **/
func SelectWarehouseProduct(id int) []model.WarehouseProduct {
	if id == 0 {
		rdb := dao.InitRedis()
		key := utils.GetWareHouseProduct()
		val2, err := rdb.Get(key).Result()
		if err == redis.Nil || err != nil {
			p := model.SelectAllWarehouse()
			if p == nil {
				return nil
			}
			ub := utils.XuLieHua(p)
			rdb.Set(key, ub, 86400*time.Second)
			return p
		} else {
			var val []model.WarehouseProduct
			_ = json.Unmarshal([]byte((val2)), &val)
			return val
		}
	} else {
		p := model.SelectWarehouseProductById(id)
		return p
	}
}

/**
 * @Author leibidong
 * @Description 添加库存信息
 * @Date  2021/7/6 19:58
 **/
func AddWarehouseProduct(ware vo.AddWareHouse) int {
	p := model.SelectIdByProductName1(ware.ProductName).ID
	if p != 0 {
		cnt := model.SelectProductCnt(p).CurrentCnt
		id := model.SelectProductCnt(p).ID
		if id != 0 {
			newCnt := cnt + ware.Cnt
			model.UpdateWareCurrentCnt(p, newCnt)
			rdb := dao.InitRedis()
			key := utils.GetWareHouseProduct()
			rdb.Del(key)
			return 1
		} else {
			t := utils.GetTime()
			ware := model.WarehouseProduct{ProductId: p, CurrentCnt: ware.Cnt, WaitCnt: 0, RealityCnt: 0, CreateTime: t, ModifiedTime: t}
			model.AddWareCurrentCnt(ware)
			rdb := dao.InitRedis()
			key := utils.GetWareHouseProduct()
			rdb.Del(key)
			return 1
		}
	} else {
		return 0
	}
}

/**
 * @Author leibidong
 * @Description 更新库存信息
 * @Date  2021/7/6 21:14
 **/
func UpdateWarehouseCnt(ware vo.UpdateWareHouse) {
	model.UpdateWareCurrentCntByWareId(utils.StringToInt(ware.Id), ware.Cnt)
	rdb := dao.InitRedis()
	key := utils.GetWareHouseProduct()
	rdb.Del(key)
}

/**
 * @Author leibidong
 * @Description 删除库存信息
 * @Date  2021/7/6 21:27
 **/
func DeleteWarehouseProduct(id int) int {
	ware := model.SelectWareproductById(id)
	if ware != (model.WarehouseProduct{}) {
		model.DeleteWareProduct(id)
		rdb := dao.InitRedis()
		key := utils.GetWareHouseProduct()
		rdb.Del(key)
		return 1
	}
	return 0

}
